home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / distutils / util.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  15.4 KB  |  458 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """distutils.util
  5.  
  6. Miscellaneous utility functions -- anything that doesn't fit into
  7. one of the other *util.py modules.
  8. """
  9. __revision__ = '$Id: util.py 68135 2009-01-01 15:46:10Z georg.brandl $'
  10. import sys
  11. import os
  12. import string
  13. import re
  14. from distutils.errors import DistutilsPlatformError
  15. from distutils.dep_util import newer
  16. from distutils.spawn import spawn
  17. from distutils import log
  18.  
  19. def get_platform():
  20.     """Return a string that identifies the current platform.  This is used
  21.     mainly to distinguish platform-specific build directories and
  22.     platform-specific built distributions.  Typically includes the OS name
  23.     and version and the architecture (as supplied by 'os.uname()'),
  24.     although the exact information included depends on the OS; eg. for IRIX
  25.     the architecture isn't particularly important (IRIX only runs on SGI
  26.     hardware), but for Linux the kernel version isn't particularly
  27.     important.
  28.  
  29.     Examples of returned values:
  30.        linux-i586
  31.        linux-alpha (?)
  32.        solaris-2.6-sun4u
  33.        irix-5.3
  34.        irix64-6.2
  35.  
  36.     Windows will return one of:
  37.        win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
  38.        win-ia64 (64bit Windows on Itanium)
  39.        win32 (all others - specifically, sys.platform is returned)
  40.  
  41.     For other non-POSIX platforms, currently just returns 'sys.platform'.
  42.     """
  43.     if os.name == 'nt':
  44.         prefix = ' bit ('
  45.         i = string.find(sys.version, prefix)
  46.         if i == -1:
  47.             return sys.platform
  48.         j = string.find(sys.version, ')', i)
  49.         look = sys.version[i + len(prefix):j].lower()
  50.         if look == 'amd64':
  51.             return 'win-amd64'
  52.         if look == 'itanium':
  53.             return 'win-ia64'
  54.         return sys.platform
  55.     if os.name != 'posix' or not hasattr(os, 'uname'):
  56.         return sys.platform
  57.     (osname, host, release, version, machine) = os.uname()
  58.     osname = string.lower(osname)
  59.     osname = string.replace(osname, '/', '')
  60.     machine = string.replace(machine, ' ', '_')
  61.     machine = string.replace(machine, '/', '-')
  62.     if osname[:5] == 'linux':
  63.         return '%s-%s' % (osname, machine)
  64.     if osname[:5] == 'sunos':
  65.         if release[0] >= '5':
  66.             osname = 'solaris'
  67.             release = '%d.%s' % (int(release[0]) - 3, release[2:])
  68.         
  69.     elif osname[:4] == 'irix':
  70.         return '%s-%s' % (osname, release)
  71.     not hasattr(os, 'uname')
  72.     if osname[:3] == 'aix':
  73.         return '%s-%s.%s' % (osname, version, release)
  74.     if osname[:6] == 'cygwin':
  75.         osname = 'cygwin'
  76.         rel_re = re.compile('[\\d.]+')
  77.         m = rel_re.match(release)
  78.         if m:
  79.             release = m.group()
  80.         
  81.     elif osname[:6] == 'darwin':
  82.         get_config_vars = get_config_vars
  83.         import distutils.sysconfig
  84.         cfgvars = get_config_vars()
  85.         macver = os.environ.get('MACOSX_DEPLOYMENT_TARGET')
  86.         if not macver:
  87.             macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
  88.         
  89.         macrelease = macver
  90.         
  91.         try:
  92.             f = open('/System/Library/CoreServices/SystemVersion.plist')
  93.         except IOError:
  94.             pass
  95.  
  96.         m = re.search('<key>ProductUserVisibleVersion</key>\\s*' + '<string>(.*?)</string>', f.read())
  97.         f.close()
  98.         if m is not None:
  99.             macrelease = '.'.join(m.group(1).split('.')[:2])
  100.         
  101.         if not macver:
  102.             macver = macrelease
  103.         
  104.         if macver:
  105.             get_config_vars = get_config_vars
  106.             import distutils.sysconfig
  107.             release = macver
  108.             osname = 'macosx'
  109.             if macrelease + '.' >= '10.4.' and '-arch' in get_config_vars().get('CFLAGS', '').strip():
  110.                 machine = 'fat'
  111.                 cflags = get_config_vars().get('CFLAGS')
  112.                 if '-arch x86_64' in cflags:
  113.                     if '-arch i386' in cflags:
  114.                         machine = 'universal'
  115.                     else:
  116.                         machine = 'fat64'
  117.                 
  118.             elif machine in ('PowerPC', 'Power_Macintosh'):
  119.                 machine = 'ppc'
  120.             
  121.         
  122.     
  123.     return '%s-%s-%s' % (osname, release, machine)
  124.  
  125.  
  126. def convert_path(pathname):
  127.     """Return 'pathname' as a name that will work on the native filesystem,
  128.     i.e. split it on '/' and put it back together again using the current
  129.     directory separator.  Needed because filenames in the setup script are
  130.     always supplied in Unix style, and have to be converted to the local
  131.     convention before we can actually use them in the filesystem.  Raises
  132.     ValueError on non-Unix-ish systems if 'pathname' either starts or
  133.     ends with a slash.
  134.     """
  135.     if os.sep == '/':
  136.         return pathname
  137.     if not pathname:
  138.         return pathname
  139.     if pathname[0] == '/':
  140.         raise ValueError, "path '%s' cannot be absolute" % pathname
  141.     pathname[0] == '/'
  142.     if pathname[-1] == '/':
  143.         raise ValueError, "path '%s' cannot end with '/'" % pathname
  144.     pathname[-1] == '/'
  145.     paths = string.split(pathname, '/')
  146.     while '.' in paths:
  147.         paths.remove('.')
  148.         continue
  149.         pathname
  150.     if not paths:
  151.         return os.curdir
  152.     return apply(os.path.join, paths)
  153.  
  154.  
  155. def change_root(new_root, pathname):
  156.     '''Return \'pathname\' with \'new_root\' prepended.  If \'pathname\' is
  157.     relative, this is equivalent to "os.path.join(new_root,pathname)".
  158.     Otherwise, it requires making \'pathname\' relative and then joining the
  159.     two, which is tricky on DOS/Windows and Mac OS.
  160.     '''
  161.     if os.name == 'posix':
  162.         if not os.path.isabs(pathname):
  163.             return os.path.join(new_root, pathname)
  164.         return os.path.join(new_root, pathname[1:])
  165.     os.name == 'posix'
  166.     if os.name == 'nt':
  167.         (drive, path) = os.path.splitdrive(pathname)
  168.         if path[0] == '\\':
  169.             path = path[1:]
  170.         
  171.         return os.path.join(new_root, path)
  172.     if os.name == 'os2':
  173.         (drive, path) = os.path.splitdrive(pathname)
  174.         if path[0] == os.sep:
  175.             path = path[1:]
  176.         
  177.         return os.path.join(new_root, path)
  178.     if os.name == 'mac':
  179.         if not os.path.isabs(pathname):
  180.             return os.path.join(new_root, pathname)
  181.         elements = string.split(pathname, ':', 1)
  182.         pathname = ':' + elements[1]
  183.         return os.path.join(new_root, pathname)
  184.     os.name == 'mac'
  185.     raise DistutilsPlatformError, "nothing known about platform '%s'" % os.name
  186.  
  187. _environ_checked = 0
  188.  
  189. def check_environ():
  190.     """Ensure that 'os.environ' has all the environment variables we
  191.     guarantee that users can use in config files, command-line options,
  192.     etc.  Currently this includes:
  193.       HOME - user's home directory (Unix only)
  194.       PLAT - description of the current platform, including hardware
  195.              and OS (see 'get_platform()')
  196.     """
  197.     global _environ_checked
  198.     if _environ_checked:
  199.         return None
  200.     if os.name == 'posix' and 'HOME' not in os.environ:
  201.         import pwd
  202.         os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]
  203.     
  204.     if 'PLAT' not in os.environ:
  205.         os.environ['PLAT'] = get_platform()
  206.     
  207.     _environ_checked = 1
  208.  
  209.  
  210. def subst_vars(s, local_vars):
  211.     """Perform shell/Perl-style variable substitution on 'string'.  Every
  212.     occurrence of '$' followed by a name is considered a variable, and
  213.     variable is substituted by the value found in the 'local_vars'
  214.     dictionary, or in 'os.environ' if it's not in 'local_vars'.
  215.     'os.environ' is first checked/augmented to guarantee that it contains
  216.     certain values: see 'check_environ()'.  Raise ValueError for any
  217.     variables not found in either 'local_vars' or 'os.environ'.
  218.     """
  219.     check_environ()
  220.     
  221.     def _subst(match, local_vars = local_vars):
  222.         var_name = match.group(1)
  223.         if var_name in local_vars:
  224.             return str(local_vars[var_name])
  225.         return os.environ[var_name]
  226.  
  227.     
  228.     try:
  229.         return re.sub('\\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)
  230.     except KeyError:
  231.         var = None
  232.         raise ValueError, "invalid variable '$%s'" % var
  233.  
  234.  
  235.  
  236. def grok_environment_error(exc, prefix = 'error: '):
  237.     """Generate a useful error message from an EnvironmentError (IOError or
  238.     OSError) exception object.  Handles Python 1.5.1 and 1.5.2 styles, and
  239.     does what it can to deal with exception objects that don't have a
  240.     filename (which happens when the error is due to a two-file operation,
  241.     such as 'rename()' or 'link()'.  Returns the error message as a string
  242.     prefixed with 'prefix'.
  243.     """
  244.     if hasattr(exc, 'filename') and hasattr(exc, 'strerror'):
  245.         if exc.filename:
  246.             error = prefix + '%s: %s' % (exc.filename, exc.strerror)
  247.         else:
  248.             error = prefix + '%s' % exc.strerror
  249.     else:
  250.         error = prefix + str(exc[-1])
  251.     return error
  252.  
  253. _wordchars_re = None
  254. _squote_re = None
  255. _dquote_re = None
  256.  
  257. def _init_regex():
  258.     global _wordchars_re, _squote_re, _dquote_re
  259.     _wordchars_re = re.compile('[^\\\\\\\'\\"%s ]*' % string.whitespace)
  260.     _squote_re = re.compile("'(?:[^'\\\\]|\\\\.)*'")
  261.     _dquote_re = re.compile('"(?:[^"\\\\]|\\\\.)*"')
  262.  
  263.  
  264. def split_quoted(s):
  265.     '''Split a string up according to Unix shell-like rules for quotes and
  266.     backslashes.  In short: words are delimited by spaces, as long as those
  267.     spaces are not escaped by a backslash, or inside a quoted string.
  268.     Single and double quotes are equivalent, and the quote characters can
  269.     be backslash-escaped.  The backslash is stripped from any two-character
  270.     escape sequence, leaving only the escaped character.  The quote
  271.     characters are stripped from any quoted string.  Returns a list of
  272.     words.
  273.     '''
  274.     if _wordchars_re is None:
  275.         _init_regex()
  276.     
  277.     s = string.strip(s)
  278.     words = []
  279.     pos = 0
  280.     while s:
  281.         m = _wordchars_re.match(s, pos)
  282.         end = m.end()
  283.         if end == len(s):
  284.             words.append(s[:end])
  285.             break
  286.         
  287.         if s[end] in string.whitespace:
  288.             words.append(s[:end])
  289.             s = string.lstrip(s[end:])
  290.             pos = 0
  291.         elif s[end] == '\\':
  292.             s = s[:end] + s[end + 1:]
  293.             pos = end + 1
  294.         elif s[end] == "'":
  295.             m = _squote_re.match(s, end)
  296.         elif s[end] == '"':
  297.             m = _dquote_re.match(s, end)
  298.         else:
  299.             raise RuntimeError, "this can't happen (bad char '%c')" % s[end]
  300.         if s[end] in string.whitespace is None:
  301.             raise ValueError, 'bad string (mismatched %s quotes?)' % s[end]
  302.         s[end] in string.whitespace is None
  303.         (beg, end) = m.span()
  304.         s = s[:beg] + s[beg + 1:end - 1] + s[end:]
  305.         pos = m.end() - 2
  306.         if pos >= len(s):
  307.             words.append(s)
  308.             break
  309.             continue
  310.     return words
  311.  
  312.  
  313. def execute(func, args, msg = None, verbose = 0, dry_run = 0):
  314.     '''Perform some action that affects the outside world (eg.  by
  315.     writing to the filesystem).  Such actions are special because they
  316.     are disabled by the \'dry_run\' flag.  This method takes care of all
  317.     that bureaucracy for you; all you have to do is supply the
  318.     function to call and an argument tuple for it (to embody the
  319.     "external action" being performed), and an optional message to
  320.     print.
  321.     '''
  322.     if msg is None:
  323.         msg = '%s%r' % (func.__name__, args)
  324.         if msg[-2:] == ',)':
  325.             msg = msg[0:-2] + ')'
  326.         
  327.     
  328.     log.info(msg)
  329.     if not dry_run:
  330.         apply(func, args)
  331.     
  332.  
  333.  
  334. def strtobool(val):
  335.     """Convert a string representation of truth to true (1) or false (0).
  336.  
  337.     True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  338.     are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
  339.     'val' is anything else.
  340.     """
  341.     val = string.lower(val)
  342.     if val in ('y', 'yes', 't', 'true', 'on', '1'):
  343.         return 1
  344.     if val in ('n', 'no', 'f', 'false', 'off', '0'):
  345.         return 0
  346.     raise ValueError, 'invalid truth value %r' % (val,)
  347.  
  348.  
  349. def byte_compile(py_files, optimize = 0, force = 0, prefix = None, base_dir = None, verbose = 1, dry_run = 0, direct = None):
  350.     '''Byte-compile a collection of Python source files to either .pyc
  351.     or .pyo files in the same directory.  \'py_files\' is a list of files
  352.     to compile; any files that don\'t end in ".py" are silently skipped.
  353.     \'optimize\' must be one of the following:
  354.       0 - don\'t optimize (generate .pyc)
  355.       1 - normal optimization (like "python -O")
  356.       2 - extra optimization (like "python -OO")
  357.     If \'force\' is true, all files are recompiled regardless of
  358.     timestamps.
  359.  
  360.     The source filename encoded in each bytecode file defaults to the
  361.     filenames listed in \'py_files\'; you can modify these with \'prefix\' and
  362.     \'basedir\'.  \'prefix\' is a string that will be stripped off of each
  363.     source filename, and \'base_dir\' is a directory name that will be
  364.     prepended (after \'prefix\' is stripped).  You can supply either or both
  365.     (or neither) of \'prefix\' and \'base_dir\', as you wish.
  366.  
  367.     If \'dry_run\' is true, doesn\'t actually do anything that would
  368.     affect the filesystem.
  369.  
  370.     Byte-compilation is either done directly in this interpreter process
  371.     with the standard py_compile module, or indirectly by writing a
  372.     temporary script and executing it.  Normally, you should let
  373.     \'byte_compile()\' figure out to use direct compilation or not (see
  374.     the source for details).  The \'direct\' flag is used by the script
  375.     generated in indirect mode; unless you know what you\'re doing, leave
  376.     it set to None.
  377.     '''
  378.     if direct is None:
  379.         if __debug__:
  380.             pass
  381.         direct = optimize == 0
  382.     
  383.     if not direct:
  384.         
  385.         try:
  386.             mkstemp = mkstemp
  387.             import tempfile
  388.             (script_fd, script_name) = mkstemp('.py')
  389.         except ImportError:
  390.             mktemp = mktemp
  391.             import tempfile
  392.             script_fd = None
  393.             script_name = mktemp('.py')
  394.  
  395.         log.info("writing byte-compilation script '%s'", script_name)
  396.         if not dry_run:
  397.             if script_fd is not None:
  398.                 script = os.fdopen(script_fd, 'w')
  399.             else:
  400.                 script = open(script_name, 'w')
  401.             script.write('from distutils.util import byte_compile\nfiles = [\n')
  402.             script.write(string.join(map(repr, py_files), ',\n') + ']\n')
  403.             script.write('\nbyte_compile(files, optimize=%r, force=%r,\n             prefix=%r, base_dir=%r,\n             verbose=%r, dry_run=0,\n             direct=1)\n' % (optimize, force, prefix, base_dir, verbose))
  404.             script.close()
  405.         
  406.         cmd = [
  407.             sys.executable,
  408.             script_name]
  409.         if optimize == 1:
  410.             cmd.insert(1, '-O')
  411.         elif optimize == 2:
  412.             cmd.insert(1, '-OO')
  413.         
  414.         spawn(cmd, dry_run = dry_run)
  415.         execute(os.remove, (script_name,), 'removing %s' % script_name, dry_run = dry_run)
  416.     else:
  417.         compile = compile
  418.         import py_compile
  419.         for file in py_files:
  420.             if file[-3:] != '.py':
  421.                 continue
  422.             
  423.             if not __debug__ or 'c':
  424.                 pass
  425.             cfile = file + 'o'
  426.             dfile = file
  427.             if prefix:
  428.                 if file[:len(prefix)] != prefix:
  429.                     raise ValueError, "invalid prefix: filename %r doesn't start with %r" % (file, prefix)
  430.                 file[:len(prefix)] != prefix
  431.                 dfile = dfile[len(prefix):]
  432.             
  433.             if base_dir:
  434.                 dfile = os.path.join(base_dir, dfile)
  435.             
  436.             cfile_base = os.path.basename(cfile)
  437.             if direct:
  438.                 if force or newer(file, cfile):
  439.                     log.info('byte-compiling %s to %s', file, cfile_base)
  440.                     if not dry_run:
  441.                         compile(file, cfile, dfile)
  442.                     
  443.                 else:
  444.                     log.debug('skipping byte-compilation of %s to %s', file, cfile_base)
  445.             newer(file, cfile)
  446.         
  447.  
  448.  
  449. def rfc822_escape(header):
  450.     '''Return a version of the string escaped for inclusion in an
  451.     RFC-822 header, by ensuring there are 8 spaces space after each newline.
  452.     '''
  453.     lines = string.split(header, '\n')
  454.     lines = map(string.strip, lines)
  455.     header = string.join(lines, '\n' + '        ')
  456.     return header
  457.  
  458.